import { useQuery, UseQueryOptions } from 'react-query';
import { useCache } from './useCache';

export function useCacheQuery<T>(
  key: string,
  fetcher: () => Promise<T>,
  options?: UseQueryOptions<T> & { cacheTime?: number }
) {
  const { getCache, setCache } = useCache();
  const cachedData = getCache(key);

  return useQuery<T>(
    key,
    async () => {
      const data = await fetcher();
      setCache(key, data, { expire: options?.cacheTime });
      return data;
    },
    {
      initialData: cachedData,
      ...options,
    }
  );
}